
package com.kugou.game.sdk.ui.widget;

import com.kugou.framework.base.BaseBroadcastReceiver;
import com.kugou.game.sdk.api.common.User;
import com.kugou.game.sdk.core.SDKActions;
import com.kugou.game.sdk.core.SDKControler;
import com.kugou.game.sdk.core.UserManager;
import com.kugou.game.sdk.utils.AppUtil;
import com.kugou.game.sdk.utils.Rx;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnPreDrawListener;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationSet;
import android.view.animation.AnticipateInterpolator;
import android.view.animation.OvershootInterpolator;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

public class ToolBar {

    public static final int LEFT_TOP = 1;

    public static final int LEFT_MID = 2;

    public static final int LEFT_BOTTOM = 3;

    public static final int RIGHT_TOP = 4;

    public static final int RIGHT_MID = 5;

    public static final int RIGHT_BOTTOM = 6;

    private Context mContext;

    private int mTouchSlop;

    private WindowManager.LayoutParams lpIndicator;

    private WindowManager.LayoutParams lpCustomView;

    private int toolBarPlace;

    private View indicatorView;

    private ToolBarCustomView customView;

    /** 执行动画的浮窗view */
    private View animationIndiView;

    /** 执行动画的view */
    private View animationView;

    /** 保存wm里添加的view */
    private List<View> views = new ArrayList<View>();

    private WindowManager wm;

    private DisplayMetrics outMetrics = new DisplayMetrics();

    /** 状态栏高度 */
    private int stateHeight;

    // 记录横屏、竖屏,横屏是1，竖屏是2，还没设置是0
    private int screenOrientation;

    private int bgIndicator, bgIndicatorSpread, bgIndicatorRedPoint, bgIndicatorLeftRedPoint,
            bgIndicatorBreatheLeft, bgIndicatorBreatheRight;

    /** 记录是否为第一次渲染浮窗 */
    private boolean isIndicatorFirst = true;

    /** 记录是否为第一次渲染浮窗 */
    private boolean isCustomViewFirst = true;

    private int indicatorView_h;

    private int indicatorView_w;

    private int customView_h;

    private int customView_w;

    /**
     * 悬浮窗图标的大小。单位为dp，要转化为px
     */
    private final int ROOTVIEW_HEIGHT = 50;

    User mUser;

    /**
     * @param context
     * @param toolBarPlace 位置参数：1、2、3、4、5、6分别为左上、左中、左下、右上、右中、右下
     * @return
     */
    private ToolBar(Context context, int toolBarPlace) {
        this.toolBarPlace = toolBarPlace;
        this.mContext = context;
        initDefaultBg();
        initVar();
        getIndicatorView();
        getCustomView();
        initToolbarReceiver();
        mUser = UserManager.getInstance().getCurrentUserInternal();
    }

    ToolBarReceiver receiver;

    private void initToolbarReceiver() {
        receiver = new ToolBarReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(SDKActions.ACTION_UPDATE_TOOLBAR_AFTER_LOGIN_SUCCESS);
        filter.addAction(SDKActions.ACTION_SET_LOGIN_PSD_SUCCESS);
        mContext.registerReceiver(receiver, filter);
    }

    private void initDefaultBg() {
        this.bgIndicator = Rx.drawable.kg_bg_toolbar_indicator_normal;
        this.bgIndicatorSpread = Rx.drawable.kg_bg_toolbar_indicator_spread;
        this.bgIndicatorRedPoint = Rx.drawable.kg_bg_toolbar_indicator_red_point;
        this.bgIndicatorLeftRedPoint = Rx.drawable.kg_bg_toolbar_indicator_left_red_point;
        this.bgIndicatorBreatheLeft = Rx.drawable.kg_bg_toolbar_indicator_breathe_left;
        this.bgIndicatorBreatheRight = Rx.drawable.kg_bg_toolbar_indicator_breathe_right;
    }

    private void initVar() {
        wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
        wm.getDefaultDisplay().getMetrics(outMetrics);

        stateHeight = AppUtil.getStateHeight(mContext);
        mTouchSlop = (int) (5 * outMetrics.density);

        lpIndicator = new WindowManager.LayoutParams();
        lpIndicator.type = WindowManager.LayoutParams.TYPE_APPLICATION;
        lpIndicator.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;

        lpIndicator.alpha = 1.0f;
        lpIndicator.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lpIndicator.width = WindowManager.LayoutParams.WRAP_CONTENT;
        lpIndicator.gravity = Gravity.TOP | Gravity.LEFT;
        lpIndicator.format = PixelFormat.TRANSPARENT;

        lpCustomView = new WindowManager.LayoutParams();
        lpCustomView.type = WindowManager.LayoutParams.TYPE_APPLICATION;
        lpCustomView.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                | WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH;

        lpCustomView.alpha = 1.0f;
        lpCustomView.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lpCustomView.width = WindowManager.LayoutParams.WRAP_CONTENT;
        lpCustomView.gravity = Gravity.TOP | Gravity.LEFT;
        lpCustomView.format = PixelFormat.TRANSPARENT;
    }

    private void initPlace(int toolBarPlace) {
        switch (toolBarPlace) {
            case LEFT_TOP:
                lpIndicator.x = 0;
                lpIndicator.y = stateHeight;
                break;
            case LEFT_MID:
                lpIndicator.x = 0;
                lpIndicator.y = (outMetrics.heightPixels - indicatorView_h) / 2;
                break;
            case LEFT_BOTTOM:
                lpIndicator.x = 0;
                lpIndicator.y = outMetrics.heightPixels - indicatorView_h;
                break;
            case RIGHT_TOP:
                lpIndicator.x = outMetrics.widthPixels - indicatorView_w;
                lpIndicator.y = stateHeight;
                break;
            case RIGHT_MID:
                lpIndicator.x = outMetrics.widthPixels - indicatorView_w;
                lpIndicator.y = (outMetrics.heightPixels - indicatorView_h) / 2;
                break;
            case RIGHT_BOTTOM:
                lpIndicator.x = outMetrics.widthPixels - indicatorView_w;
                lpIndicator.y = outMetrics.heightPixels - indicatorView_h;
                break;

            default:
                Toast.makeText(mContext, "请传入正确的位置参数！", Toast.LENGTH_SHORT).show();
                break;
        }
        setCustomPlace();
    }

    private void setCustomPlace() {
        if (lpIndicator.x < (outMetrics.widthPixels - indicatorView_w) / 2) {
            // 为了customview与toolbar衔接更自然，往左偏移5px
            lpCustomView.x = lpIndicator.x + indicatorView_w - 5;
        } else {
            lpCustomView.x = lpIndicator.x - customView.getWidth();
        }
        lpCustomView.y = lpIndicator.y;
    }

    private OnTouchListener onTouchListener = new OnTouchListener() {
        private boolean isMoved = false;

        private int startX, startY;

        private int rawStartX, rawStartY;

        @Override
        public boolean onTouch(View v, MotionEvent ev) {
            int action = ev.getAction();
            switch (action) {
                case MotionEvent.ACTION_DOWN:
                    startX = (int) ev.getX();
                    startY = (int) ev.getY();
                    rawStartX = (int) ev.getRawX();
                    rawStartY = (int) ev.getRawY();

                    mUiHandler.removeMessages(MSG_EXECUTE_HIDE_ANIMATION);
                    mUiHandler.removeMessages(MSG_EXECUTE_SCROLL);
                    indicatorView.scrollTo(0, 0);
                    setAlpha(indicatorView, 1.0f);
                    break;
                case MotionEvent.ACTION_MOVE:
                    if (Math.abs(ev.getRawX() - rawStartX) < mTouchSlop
                            || Math.abs(ev.getRawY() - rawStartY) < mTouchSlop) {
                        return true;
                    }
                    if (customView.getVisibility() != View.VISIBLE) {
                        lpIndicator.x = (int) (ev.getRawX() - startX);
                        lpIndicator.y = (int) (ev.getRawY() - startY);
                        if (lpIndicator.y < stateHeight) {
                            lpIndicator.y = stateHeight;
                        }
                        updateViewLayout(indicatorView, lpIndicator);
                    }
                    isMoved = true;
                    setCustomViewVisibility(View.GONE, true);
                    break;
                case MotionEvent.ACTION_UP:
                    if (!isMoved) {
                        if (customView.getVisibility() == View.VISIBLE) {
                            setCustomViewVisibility(View.GONE, true);
                        } else {
                            setCustomViewVisibility(View.VISIBLE, true);
                        }
                    } else {
                        if (outMetrics != null) {
                            int i = (outMetrics.widthPixels - indicatorView_w) / 2;
                            if (Math.abs(lpIndicator.x) >= i) {
                                lpIndicator.x = outMetrics.widthPixels - indicatorView_w;
                            } else if (Math.abs(lpIndicator.x) < i) {
                                lpIndicator.x = 0;
                            } else {
                            }
                            setCustomPlace();
                            updateViewLayout(indicatorView, lpIndicator);
                            updateViewLayout(customView, lpCustomView);
                        }
                        isMoved = false;
                        updateIndicatorBg();
                        sendMessageToHideIndicatorView();
                    }
                    break;
            }
            return true;
        }
    };

    private View getIndicatorView() {
        if (indicatorView == null) {
            DisplayMetrics metric = new DisplayMetrics();
            wm.getDefaultDisplay().getMetrics(metric);
            int indicatorView_h = (int) (ROOTVIEW_HEIGHT * metric.density);

            ImageView imageView = new ImageView(mContext);
            LayoutParams lp = new LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT);
            imageView.setLayoutParams(lp);
            LinearLayout linerlLayout = new LinearLayout(mContext);
            linerlLayout.addView(imageView);
            animationIndiView = imageView;
            indicatorView = linerlLayout;
            updateIndicatorBg();
        }
        indicatorView.setOnTouchListener(onTouchListener);
        ViewTreeObserver viewTreeObserver = indicatorView.getViewTreeObserver();
        viewTreeObserver.addOnPreDrawListener(new OnPreDrawListener() {

            @Override
            public boolean onPreDraw() {
                if (indicatorView == null) {
                    return false;
                }
                // 只需要获取一次就可以了
                if (isIndicatorFirst) {
                    isIndicatorFirst = false;
                    indicatorView_h = indicatorView.getHeight();
                    indicatorView_w = indicatorView.getWidth();
                    if (indicatorView_w == 0) {
                        DisplayMetrics metric = new DisplayMetrics();
                        wm.getDefaultDisplay().getMetrics(metric);
                        indicatorView_w = (int) (ROOTVIEW_HEIGHT * metric.density);
                    }
                    initPlace(toolBarPlace);
                    updateViewLayout(indicatorView, lpIndicator);
                    updateViewLayout(customView, lpCustomView);
                }

                return true;
            }
        });
        return indicatorView;
    }

    private View getCustomView() {
        if (customView == null) {
            ToolBarCustomView view = new ToolBarCustomView(mContext);
            view.setToolBar(this);
            customView = view;
            customView.setOnTouchListener(new OnTouchListener() {

                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    switch (event.getAction()) {
                        case MotionEvent.ACTION_OUTSIDE:
                            if (!isInChangeImageZone(indicatorView, (int) event.getRawX(),
                                    (int) event.getRawY())) {
                                if (customView.getVisibility() == View.VISIBLE) {
                                    setCustomViewVisibility(View.GONE, false);
                                } else {

                                }
                            }
                            return true;

                        default:
                            break;
                    }
                    return false;
                }
            });
            if (customView instanceof ViewGroup) {
                try {
                    View childView = ((ViewGroup) customView).getChildAt(0);
                    if (childView instanceof ViewGroup) {
                        animationView = childView;
                    }
                } catch (Exception e) {
                }
            }
        }

        ViewTreeObserver viewTreeObserver = customView.getViewTreeObserver();
        viewTreeObserver.addOnPreDrawListener(new OnPreDrawListener() {

            @Override
            public boolean onPreDraw() {
                if (customView == null) {
                    return false;
                }
                // 只需要获取一次就可以了
                if (isCustomViewFirst) {
                    isCustomViewFirst = false;
                    customView_h = customView.getHeight();
                    customView_w = customView.getWidth();
                    if (customView_w == 0) {
                        DisplayMetrics metric = new DisplayMetrics();
                        wm.getDefaultDisplay().getMetrics(metric);
                        if (SDKControler.isNeedHideGameCenter()) {
                            customView_w = (int) (metric.density * 65 * 2);
                        } else {
                            customView_w = (int) (metric.density * 65 * 3);
                        }
                    }
                    initPlace(toolBarPlace);
                    updateViewLayout(indicatorView, lpIndicator);
                    updateViewLayout(customView, lpCustomView);
                }

                return true;
            }
        });
        return customView;
    }

    private Rect mChangeImageBackgroundRect = null;

    private boolean isInChangeImageZone(View view, int x, int y) {
        if (null == view) {
            return false;
        }
        if (null == mChangeImageBackgroundRect) {
            mChangeImageBackgroundRect = new Rect();
        }
        view.getDrawingRect(mChangeImageBackgroundRect);

        int[] location = new int[2];
        view.getLocationOnScreen(location);

        mChangeImageBackgroundRect.right = mChangeImageBackgroundRect.right
                - mChangeImageBackgroundRect.left + location[0];
        mChangeImageBackgroundRect.bottom = mChangeImageBackgroundRect.bottom
                - mChangeImageBackgroundRect.top + location[1];
        mChangeImageBackgroundRect.left = location[0];
        mChangeImageBackgroundRect.top = location[1];

        return mChangeImageBackgroundRect.contains(x, y);
    }

    /**
     * 判断当前是横屏竖屏，进行位置的重新设置
     */
    public void switchScreenOrientation() {
        wm.getDefaultDisplay().getMetrics(outMetrics);
        if (outMetrics.widthPixels <= outMetrics.heightPixels) {
            if (screenOrientation == 2) {
                return;
            }
            screenOrientation = 2;
        } else {
            if (screenOrientation == 1) {
                return;
            }
            screenOrientation = 1;
        }
        initPlace(toolBarPlace);
    }

    private void addView(View view, WindowManager.LayoutParams lp) {
        try {
            if (!views.contains(view)) {
                views.add(view);
                wm.addView(view, lp);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void updateViewLayout(View view, WindowManager.LayoutParams lp) {
        try {
            if (views.contains(view)) {
                wm.updateViewLayout(view, lp);
            } else {
                addView(view, lp);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void removeView(View view) {
        try {
            if (views.contains(view)) {
                views.remove(view);
                wm.removeView(view);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据不同场景创建不同的动画
     * 
     * @param visibility
     * @param isLeft
     * @return
     */
    private AnimationSet createAnimation(int visibility, boolean isLeft) {
        AnimationSet animationSet = new AnimationSet(true);
        Animation alphaAnimation;
        Animation scaleAnimation;
        if (visibility == View.VISIBLE) {
            alphaAnimation = new AlphaAnimation(0.1f, 1.0f);
            if (isLeft) {
                scaleAnimation = new ScaleAnimation(0.0f, 1.0f, 0.0f, 1.0f,
                        Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.5f);
            } else {
                scaleAnimation = new ScaleAnimation(0.0f, 1.0f, 0.0f, 1.0f,
                        Animation.RELATIVE_TO_SELF, 1.0f, Animation.RELATIVE_TO_SELF, 0.5f);
            }
            animationSet.setInterpolator(new OvershootInterpolator());
            animationSet.setDuration(150);
        } else {
            alphaAnimation = new AlphaAnimation(1.0f, 0.1f);
            if (isLeft) {
                scaleAnimation = new ScaleAnimation(1.0f, 0.0f, 1.0f, 0.0f,
                        Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.5f);
            } else {
                scaleAnimation = new ScaleAnimation(1.0f, 0.0f, 1.0f, 0.0f,
                        Animation.RELATIVE_TO_SELF, 1.0f, Animation.RELATIVE_TO_SELF, 0.5f);
            }
            animationSet.setInterpolator(new AnticipateInterpolator());
            animationSet.setDuration(250);
            animationSet.setAnimationListener(animationListener);
        }
        animationSet.addAnimation(scaleAnimation);
        animationSet.addAnimation(alphaAnimation);
        return animationSet;
    }

    private AnimationListener animationListener = new AnimationListener() {

        @Override
        public void onAnimationStart(Animation animation) {

        }

        @Override
        public void onAnimationRepeat(Animation animation) {

        }

        @Override
        public void onAnimationEnd(Animation animation) {
            customView.setVisibility(View.GONE);
            // 发送handler，在5s后执行悬浮窗隐藏一半的动画
            sendMessageToHideIndicatorView();
        }
    };

    private AnimationListener hideAnimationListener = new AnimationListener() {

        @Override
        public void onAnimationStart(Animation animation) {

        }

        @Override
        public void onAnimationRepeat(Animation animation) {

        }

        @Override
        public void onAnimationEnd(Animation animation) {
            if (lpIndicator.x == 0) {
                indicatorView.scrollTo(indicatorView_w / 2, 0);
            } else if (lpIndicator.x == outMetrics.widthPixels - indicatorView_w) {
                indicatorView.scrollTo(-indicatorView_w / 2, 0);
            }
        }
    };

    /**
     * 发送通知去把浮窗隐藏一半
     */
    private void sendMessageToHideIndicatorView() {
        mUiHandler.removeMessages(MSG_EXECUTE_HIDE_ANIMATION);
        mUiHandler.sendEmptyMessageDelayed(MSG_EXECUTE_HIDE_ANIMATION, 5000);
    }

    private final int MSG_EXECUTE_HIDE_ANIMATION = 0x0001;

    private final int MSG_EXECUTE_SCROLL = 0x0002;

    protected Handler mUiHandler = new UiHandler(this);

    private static class UiHandler extends Handler {
        private final WeakReference<ToolBar> mFragmentReference;

        public UiHandler(ToolBar activity) {
            mFragmentReference = new WeakReference<ToolBar>(activity);
        }

        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (mFragmentReference.get() != null) {
                mFragmentReference.get().handleUiMessage(msg);
            }
        };
    }

    /**
     * 记录位移次数
     */
    private int scrollNum;

    /**
     * 处理更新UI任务
     * 
     * @param msg
     */
    public void handleUiMessage(Message msg) {
        switch (msg.what) {
            case MSG_EXECUTE_HIDE_ANIMATION:
                if (animationIndiView != null) {
                    scrollNum = 0;
                    mUiHandler.sendEmptyMessage(MSG_EXECUTE_SCROLL);
                }
                break;
            case MSG_EXECUTE_SCROLL:
                if (indicatorView == null) {
                    return;
                }
                int flag = -1;
                if (lpIndicator.x == 0) {
                    flag = 1;
                } else {
                    flag = -1;
                }
                int scrollX = indicatorView.getScrollX();
                if (Math.abs(scrollX) >= indicatorView_w * 8 / 13) {
                    setAlpha(indicatorView, 0.5f);
                    scrollNum = 0;
                    return;
                }
                int balance = indicatorView_w * 8 / 13 - indicatorView_w / 40 * scrollNum;
                if (balance > indicatorView_w / 40) {
                    scrollNum++;
                    indicatorView.scrollBy(flag * indicatorView_w / 40, 0);
                    mUiHandler.sendEmptyMessageDelayed(MSG_EXECUTE_SCROLL, 15);
                } else {
                    indicatorView.scrollBy(flag * balance, 0);
                    setAlpha(indicatorView, 0.5f);
                    scrollNum = 0;
                }
                break;
        }

    }

    /**
     * 设置透明度
     * 
     * @param view
     * @param alpha
     */
    @SuppressLint("NewApi")
    private void setAlpha(View view, float alpha) {
        if (AppUtil.getSdkInt() > 10) {
            view.setAlpha(alpha);
        }
    }

    /**
     * 设置工具栏展开或者收起
     * 
     * @param visibility
     */
    public void setCustomViewVisibility(int visibility) {
        setCustomViewVisibility(visibility, false);
    }

    /**
     * @param visibility View.GONE or View.VISIBLE
     * @param needAnimation 是否需要动画
     */
    public void setCustomViewVisibility(int visibility, boolean needAnimation) {
        if (visibility == View.VISIBLE) {
            customView.setVisibility(View.VISIBLE);
            customView.updateUsercenterIndicatorBg();
            customView.updateGiftbagIndicatorVisibility();
            customView.updateSetLoginPsdViewState();
            customView.setViewStateByPlace(lpIndicator.x == 0 ? true : false);
            if (needAnimation && animationView != null) {
                if (animationView.getAnimation() != null) {
                    animationView.getAnimation().cancel();
                }
                animationView.startAnimation(createAnimation(View.VISIBLE,
                        lpIndicator.x == 0 ? true : false));
            }

            if (mUser != null && !mUser.isSetKugouPsd()) {
                if (lpIndicator.x < 0
                        || (lpIndicator.x >= 0 && lpIndicator.x <= (outMetrics.widthPixels - indicatorView_w) / 2)) {
                    animationIndiView.setBackgroundResource(bgIndicatorBreatheLeft);
                } else {
                    animationIndiView.setBackgroundResource(bgIndicatorBreatheRight);
                }
            } else {
                animationIndiView.setBackgroundResource(bgIndicatorSpread);
            }

        } else {
            updateIndicatorBg();
            if (!needAnimation || animationView == null) {
                customView.setVisibility(View.GONE);
                sendMessageToHideIndicatorView();
            } else {
                if (animationView.getAnimation() != null) {
                    animationView.getAnimation().cancel();
                }
                animationView.startAnimation(createAnimation(View.GONE, lpIndicator.x == 0 ? true
                        : false));
            }
        }
    }

    /**
     * 显示浮窗
     */
    public void show() {
        views.clear();
        addView(indicatorView, lpIndicator);
        addView(customView, lpCustomView);
        // 检查是否要显示呼吸灯效果
        checkAccoutPsdState();
    }

    private void checkAccoutPsdState() {
        if (mUser != null) {
            boolean setPsd = mUser.isSetKugouPsd();
            if (!setPsd) {
                startBreatheAnimation();
            }
        }
    }

    private void startBreatheAnimation() {
        if (animationIndiView != null) {
            if (animationIndiView.getAnimation() != null) {
                animationIndiView.getAnimation().cancel();
            }

            animationIndiView.setDrawingCacheEnabled(false);
            AnimationSet animationBreathe = new AnimationSet(true);
            Animation alphaAnimation = new AlphaAnimation(1.0f, 0.6f);
            alphaAnimation.setDuration(800);
            alphaAnimation.setRepeatCount(Animation.INFINITE);
            alphaAnimation.setRepeatMode(Animation.REVERSE);
            Animation scaleAnimation = new ScaleAnimation(1.0f, 0.95f, 1.0f, 0.95f,
                    Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
            scaleAnimation.setDuration(800);
            scaleAnimation.setRepeatCount(Animation.INFINITE);
            scaleAnimation.setRepeatMode(Animation.REVERSE);
            animationBreathe.addAnimation(alphaAnimation);
            animationBreathe.addAnimation(scaleAnimation);
            animationIndiView.startAnimation(animationBreathe);
        }
    }

    private void removeBreatheAnimation() {
        if (animationIndiView != null) {
            animationIndiView.clearAnimation();
            if (animationIndiView.getAnimation() != null) {
                animationIndiView.getAnimation().cancel();
            }
        }
    }

    /**
     * 隐藏浮窗
     */
    public void hide() {
        removeView(indicatorView);
        removeView(customView);
    }

    /**
     * 在界面被销毁前，必须执行该方法，建议在onDestroy()里执行
     */
    public void recycle() {
        if (receiver != null) {
            mContext.unregisterReceiver(receiver);
            receiver = null;
        }

        if (animationIndiView != null) {
            animationIndiView.clearAnimation();
        }

        if (animationView != null) {
            animationIndiView.clearAnimation();
        }

        if (wm != null) {
            removeView(customView);
            removeView(indicatorView);
            customView = null;
            indicatorView = null;
            wm = null;
        }
    }

    /**
     * 设置浮窗布局
     * 
     * @param view
     */
    public void setIndicatorView(View view) {
        isIndicatorFirst = true;
        this.indicatorView = view;
    }

    /**
     * 设置工具栏布局
     * 
     * @param view
     */
    public void setCustomView(ToolBarCustomView view) {
        isCustomViewFirst = true;
        this.customView = view;
    }

    /**
     * @param bgIndicatorNormal 浮窗（indicatorView）平常时显示的背景图片id
     * @param bgIndicatorLeft customView可见时，浮窗的背景图片id
     */
    public void setBgResourceId(int bgIndicator, int bgIndicatorSpread) {
        this.bgIndicator = bgIndicator;
        this.bgIndicatorSpread = bgIndicatorSpread;
    }

    /**
     * 刷新悬浮窗背景显示
     */
    public void updateIndicatorBg() {
        if (mUser == null || indicatorView == null || animationIndiView == null) {// 防止CP在未登录前就调用悬浮窗
            return;
        }

        if (!mUser.isSetKugouPsd()) {
            if (lpIndicator.x < 0
                    || (lpIndicator.x >= 0 && lpIndicator.x <= (outMetrics.widthPixels - indicatorView_w) / 2)) {
                animationIndiView.setBackgroundResource(bgIndicatorBreatheLeft);
            } else {
                animationIndiView.setBackgroundResource(bgIndicatorBreatheRight);
            }
        } else if (mUser.getUnreadmails() > 0 && !mUser.isUnreadMailReminded()) {
            if (lpIndicator.x < 0
                    || (lpIndicator.x >= 0 && lpIndicator.x <= (outMetrics.widthPixels - indicatorView_w) / 2)) {
                animationIndiView.setBackgroundResource(bgIndicatorRedPoint);
            } else {
                animationIndiView.setBackgroundResource(bgIndicatorLeftRedPoint);
            }
        } else if (mUser.isGameCenterNeedRedPointRemind()) {
            if (lpIndicator.x < 0
                    || (lpIndicator.x >= 0 && lpIndicator.x <= (outMetrics.widthPixels - indicatorView_w) / 2)) {
                animationIndiView.setBackgroundResource(bgIndicatorRedPoint);
            } else {
                animationIndiView.setBackgroundResource(bgIndicatorLeftRedPoint);
            }
        } else {
            animationIndiView.setBackgroundResource(bgIndicator);
        }
    }

    /**
     * 描述:登录或注册成功的广播接收器（用于更新悬浮窗红点）
     * 
     * @author liux
     * @since 2014-9-12 上午09:59:17
     */
    class ToolBarReceiver extends BaseBroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            super.onReceive(context, intent);
            String action = intent.getAction();
            if (SDKActions.ACTION_UPDATE_TOOLBAR_AFTER_LOGIN_SUCCESS.equals(action)) {
                if (mUser != null && mUser.getUnreadmails() > 0) {
                    if (customView != null && indicatorView != null) {
                        updateIndicatorBg();
                        customView.updateUsercenterIndicatorBg();
                    }
                }
            } else if (SDKActions.ACTION_SET_LOGIN_PSD_SUCCESS.equals(action)) {
                removeBreatheAnimation();
                updateIndicatorBg();
                if (customView != null) {
                    customView.updateSetLoginPsdViewState();
                }
            }
        }
    }

    /**
     * 登录或注册成功后，创建并发送刷新悬浮窗的广播
     * 
     * @param context
     */
    public static void createAndSendUpdateIntent(Context context) {
        Intent intent = new Intent(SDKActions.ACTION_UPDATE_TOOLBAR_AFTER_LOGIN_SUCCESS);
        context.sendBroadcast(intent);
    }
}
